import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntApp } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import Login from './components/Login';
import Layout from './components/Layout';
import Dashboard from './components/Dashboard';
import UserManagement from './components/UserManagement';
import Settings from './components/Settings';
import ProtectedRoute from './components/ProtectedRoute';
import type { User } from './types';

const App: React.FC = () => {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  // 检查本地存储的登录状态
  useEffect(() => {
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
      try {
        setCurrentUser(JSON.parse(savedUser));
      } catch (error) {
        localStorage.removeItem('currentUser');
      }
    }
    setLoading(false);
  }, []);

  // 处理登录成功
  const handleLoginSuccess = (user: User) => {
    setCurrentUser(user);
    localStorage.setItem('currentUser', JSON.stringify(user));
  };

  // 处理退出登录
  const handleLogout = () => {
    setCurrentUser(null);
    localStorage.removeItem('currentUser');
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <ConfigProvider locale={zhCN}>
      <AntApp>
        <Router>
          <Routes>
            {/* 登录页面 */}
            <Route
              path="/login"
              element={
                currentUser ? (
                  <Navigate to="/dashboard" replace />
                ) : (
                  <Login onLoginSuccess={handleLoginSuccess} />
                )
              }
            />

            {/* 受保护的路由 */}
            <Route
              path="/dashboard"
              element={
                <ProtectedRoute currentUser={currentUser}>
                  <Layout currentUser={currentUser!} onLogout={handleLogout}>
                    <Dashboard />
                  </Layout>
                </ProtectedRoute>
              }
            />

            <Route
              path="/users"
              element={
                <ProtectedRoute currentUser={currentUser}>
                  <Layout currentUser={currentUser!} onLogout={handleLogout}>
                    <UserManagement />
                  </Layout>
                </ProtectedRoute>
              }
            />

            {/* 管理员专用路由 */}
            <Route
              path="/settings"
              element={
                <ProtectedRoute currentUser={currentUser} requiredRole="admin">
                  <Layout currentUser={currentUser!} onLogout={handleLogout}>
                    <Settings />
                  </Layout>
                </ProtectedRoute>
              }
            />

            {/* 默认重定向 */}
            <Route
              path="/"
              element={
                currentUser ? (
                  <Navigate to="/dashboard" replace />
                ) : (
                  <Navigate to="/login" replace />
                )
              }
            />

            {/* 404 页面 */}
            <Route
              path="*"
              element={
                <div style={{ 
                  display: 'flex', 
                  justifyContent: 'center', 
                  alignItems: 'center', 
                  height: '100vh',
                  flexDirection: 'column'
                }}>
                  <h1>404</h1>
                  <p>页面不存在</p>
                  <button onClick={() => window.history.back()}>返回</button>
                </div>
              }
            />
          </Routes>
        </Router>
      </AntApp>
    </ConfigProvider>
  );
};

export default App;
